/**
 * The table model of the ItemClass table
 * 
 * @author remo.lemma@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui.table.itemclass;

import javax.swing.table.DefaultTableModel;

import ch.unisi.inf.projects.java.uom.elements.Element;
import ch.unisi.inf.projects.java.uom.elements.ItemClass;

public class UOMItemClassTableModel extends DefaultTableModel
{
	/** We are not going to serialize this class atm */
    private static final long serialVersionUID = -1L;
	    
    public UOMItemClassTableModel ()
    {
		super();
	}

    public Class<?> getColumnClass (final int index)
    {
    	return ItemClass.class;
    }
    
    public void addRow (final ItemClass e)
    {
    	addRow(new Object[] { e });
    }
    
    public void removeRow (final Element e)
    {
    	final int row = findRow(e);
    	if (row == -1)
    		return;
    	removeRow(row);
    }
    
    private int findRow (final Element e)
    {
    	for (int i = 0; i < this.getRowCount(); i++) {
    		if (this.getValueAt(i, 0).toString().toUpperCase().equals(e.toString().toUpperCase()))
    			return i;
    	}
    	return -1;
    }
    
    public void clear ()
    {
    	for (int i = 0; i < this.getRowCount(); i++)
    		this.removeRow(i);
    	this.setRowCount(0);
    }
    
    public boolean isCellEditable (final int row, final int column)
    {
    	return false;
    }
    
    public void updateRow (final Element e)
    {
    	final int row = findRow(e);
    	if (row == -1)
    		return;
    	this.setValueAt(e, row, 0);
    }
    
    public Object getValueAt (final int row, final int col)
    {
    	if (row >= this.getRowCount())
    		return super.getValueAt(this.getRowCount() - 1, col);
    	return super.getValueAt(row, col);
    }
}
